<?php
namespace app\admin\controller;
use app\common\logic\MessageLogic;
use think\AjaxPage;
use Config;
use think\Page;
use think\Db;
use app\admin\logic\UsersLogic;
use think\Loader;

class User extends Base {
    public function index(){
        $action = [
            ['button' => 'a', 'text' => '新增', 'type' => 'add', 'href' => url('admin/admin_info') ,'msg' => ''],
            ['button' => 'button', 'text' => '删除', 'type' => 'delete', 'href' => url('admin/adminHandle'), 'msg' => '确定要删除吗?']
        ];
        $this->assign('action', $action);
        return $this->fetch();
    }

    /**
     * 会员列表
     */
    public function ajaxindex(){
        //获取数据
        $data = input('get.');
        $draw = $data['draw'];    //这个值直接返回给前台
        //关键字搜索
        $keyword = $data['keywords'];
        $where = [];
        if ($keyword) {
            $where[] = array('mobile|email','like', '%'.$keyword.'%');
        }
        //定义查询数据总记录数sql
        $recordsTotal = M('users')->count();
        //定义过滤条件查询过滤后的记录数sql
        $recordsFiltered =  M('users')->where($where)->count();
        //排序条件
        $orderArr = [1=>'user_id', 4=>'total_amount', 7=>'user_money', 8=>'pay_points', 9=>'reg_time'];
        //获取要排序的字段
        $orderField = (empty($orderArr[$data['order']['0']['column']])) ? 'user_id' : $orderArr[$data['order']['0']['column']];
        //需要空格,防止字符串连接在一块
        $order = $orderField.' '.$data['order']['0']['dir'];
        //查询数据
        $userList = M('users')->where($where)->order($order)->limit(intval($data['start']), intval($data['length']))->select();
        $level = M('user_level')->column('level_id,level_name');
        //处理数据
        if(!empty($userList)) {
            foreach ($userList as $key => $value) {
                //级别
                $userList[$key]['level_name'] = $level[$value['level']];
                //邮箱验证
                $userList[$key]['email_status'] = '';
                if ($value['email_validated'] == 0 || empty($value['email'])){
                    $userList[$key]['email_status'] = '(未验证)';
                }
                //手机验证
                $userList[$key]['mobile_status'] = '';
                if ($value['mobile_validated'] == 0 || empty($value['mobile'])){
                    $userList[$key]['mobile_status'] = '(未验证)';
                }
                $userList[$key]['reg_time'] = date("Y-m-d H:i:s",$value['reg_time']);
                $userList[$key]['recordsFiltered'] = $recordsFiltered;
            }
        }
        //拼接要返回的数据
        $list = array(
            "draw" => intval($draw),
            "recordsTotal" => intval($recordsTotal),
            "recordsFiltered"=>intval($recordsFiltered),
            "data" => $userList,
        );
        return $list;
        $this->success();
        // 搜索条件
        $condition = array();
        input('mobile') ? $condition['mobile'] = input('mobile') : false;
        input('email') ? $condition['email'] = input('email') : false;

        input('parent_id') && ($condition['parent_id'] = input('parent_id')); // 查看一级下线人有哪些
        $sort_order = input('order_by', 'user_id').' '.input('sort', 'desc');

        $count = M('users')->where($condition)->count();

        $Page  = new AjaxPage($count, Config::get('paginate.list_rows'));

        //  搜索条件下 分页赋值
        foreach($condition as $key=>$val) {
            $Page->parameter[$key]   =   urlencode($val);
        }
        $userList = M('users')->where($condition)->order($sort_order)->limit($Page->firstRow.','.$Page->listRows)->select();
        $user_id_arr = get_arr_column($userList, 'user_id');
        if(!empty($user_id_arr))
        {
            $parent_id = DB::query("select parent_id,count(1) as count  from ". Config::get('database.prefix') ."users where parent_id in(".  implode(',', $user_id_arr).")  group by parent_id");
            $parent_id = convert_arr_key($parent_id,'parent_id');
          
            $show = $Page->show();
            $this->assign('userList',$userList);
            $this->assign('level',M('user_level')->column('level_id,level_name'));
            $this->assign('page',$show);// 赋值分页输出
            $this->assign('pager',$Page);
            return $this->fetch();
        }
	}

    /**
     * 会员详细信息查看
     */
    public function detail(){
        $uid = $this->request->param('id');
        $user = M('users')->where(array('user_id'=>$uid))->find();
        if(!$user)
            exit($this->error('会员不存在'));
        if($this->request->isPost()){
            //  会员信息编辑
            $password = input('post.password');
            $password2 = input('post.password2');
            if($password != '' && $password != $password2){
                exit($this->error('两次输入密码不同'));
            }
            if($password == '' && $password2 == ''){
                unset($_POST['password']);
            }else{
                $_POST['password'] = encrypt($_POST['password']);
            }
            unset($_POST['password2']);
            if(!empty($_POST['email']))
            {   $email = trim($_POST['email']);
                $c = M('users')->where("user_id != $uid and email = '$email'")->count();
                $c && exit($this->error('邮箱不得和已有用户重复'));
            }            
            
            if(!empty($_POST['mobile']))
            {   $mobile = trim($_POST['mobile']);
                $c = M('users')->where("user_id != $uid and mobile = '$mobile'")->count();
                $c && exit($this->error('手机号不得和已有用户重复'));
            }            
            $row = M('users')->where(array('user_id'=>$uid))->update($_POST);
            if($row)
                exit($this->success('修改成功'));
            exit($this->error('未作内容修改或修改失败'));
        }
        
       
        $sql="select * from `__PREFIX__user_level`";
        $level = Db::query($sql);
        $this->assign('level', $level);
        $this->assign('user',$user);
        return $this->fetch();
    }
    
    public function add_user(){
    	if($this->request->isPost()){
    		$data = input('post.');
			$user_obj = new UsersLogic();
			$res = $user_obj->addUser($data);
			if($res['status'] == 1){
				$this->success('添加成功',url('User/index'));exit;
			}else{
				$this->error('添加失败,'.$res['msg'],url('User/index'));
			}
    	}
    	return $this->fetch();
    }
    
    public function export_user(){
    	$strTable ='<table width="500" border="1">';
    	$strTable .= '<tr>';
    	$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">会员ID</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="100">会员昵称</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">会员等级</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">手机号</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">邮箱</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">注册时间</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">最后登陆</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">余额</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">积分</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">累计消费</td>';
    	$strTable .= '</tr>';
    	$count = M('users')->count();
    	$p = ceil($count/5000);
    	for($i=0;$i<$p;$i++){
    		$start = $i*5000;
    		$end = ($i+1)*5000;
    		$userList = M('users')->order('user_id')->limit($start.','.$end)->select();
    		if(is_array($userList)){
    			foreach($userList as $k=>$val){
    				$strTable .= '<tr>';
    				$strTable .= '<td style="text-align:center;font-size:12px;">'.$val['user_id'].'</td>';
    				$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['nickname'].' </td>';
    				$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['level'].'</td>';
    				$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['mobile'].'</td>';
    				$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['email'].'</td>';
    				$strTable .= '<td style="text-align:left;font-size:12px;">'.date('Y-m-d H:i',$val['reg_time']).'</td>';
    				$strTable .= '<td style="text-align:left;font-size:12px;">'.date('Y-m-d H:i',$val['last_login']).'</td>';
    				$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['user_money'].'</td>';
    				$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['pay_points'].' </td>';
    				$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['total_amount'].' </td>';
    				$strTable .= '</tr>';
    			}
    			unset($userList);
    		}
    	}
    	$strTable .='</table>';
    	downloadExcel($strTable,'users_'.$i);
    	exit();
    }

    /**
     * 用户收货地址查看
     */
    public function address(){
        $uid = $this->request->param('id');
        $lists = M('user_address')->where(array('user_id'=>$uid))->select();
        $regionList = get_region_list();
        $this->assign('regionList',$regionList);
        $this->assign('lists',$lists);
        return $this->fetch();
    }

    /**
     * 删除会员
     */
    public function delete(){
        $uid = input('id/d');
        $row = M('users')->where(array('user_id'=>$uid))->delete();
		
	
        if($row){
            $this->success('成功删除会员');
        }else{
            $this->error('操作失败');
        }
    }
    /**
     * 删除会员
     */
    public function ajax_delete(){
        $uid = input('id');
        if($uid){
            $row = M('users')->where(array('user_id'=>$uid))->delete();
            if($row !== false){
                //把关联的第三方账号删除
                M('OauthUsers')->where(array('user_id'=>$uid))->delete();
                $this->ajaxReturn(array('status' => 1, 'msg' => '删除成功', 'data' => ''));
            }else{
                $this->ajaxReturn(array('status' => 0, 'msg' => '删除失败', 'data' => ''));
            }
        }else{
            $this->ajaxReturn(array('status' => 0, 'msg' => '参数错误', 'data' => ''));
        }
    }

    /**
     * 账户资金记录
     */
    public function account_log(){
        //echo THINK_VERSION;exit;
        $user_id = $this->request->param('id');
        //获取类型
        $type = input('get.type');
        //获取记录总数
        $count = M('account_log')->where(array('user_id'=>$user_id))->count();
        $page = new Page($count, Config::get('paginate.list_rows'));
        $lists  = M('account_log')->where(array('user_id'=>$user_id))->order('change_time desc')->limit($page->firstRow.','.$page->listRows)->select();
        $this->assign('user_id',$user_id);
        $this->assign('page',$page->show());
        $this->assign('lists',$lists);
        return $this->fetch();
    }

    /**
     * 账户资金调节
     */
    public function account_edit(){
        $user_id = input('user_id');
        if(!$user_id > 0) $this->error('参数有误');
        $user = M('users')->field('user_id,nickname,user_money,frozen_money,pay_points,is_lock')->where('user_id',$user_id)->find();
        if($this->request->isPost()){
            $desc = input('post.desc');
            if(!$desc)
                exit(json_encode(['status'=>0,'msg'=>"请填写操作说明"]));
            //加减用户资金
            $m_op_type = input('post.money_act_type');
            $user_money = input('post.user_money/f');
            $user_money =  $m_op_type ? $user_money : 0-$user_money;
            //加减用户积分
            $p_op_type = input('post.point_act_type');
            $pay_points = input('post.pay_points/d');
            $pay_points =  $p_op_type ? $pay_points : 0-$pay_points;
            //加减冻结资金
            $f_op_type = input('post.frozen_act_type');
            $revision_frozen_money = input('post.frozen_money/f');
            if( $revision_frozen_money != 0){    //有加减冻结资金的时候
                $frozen_money =  $f_op_type ? $revision_frozen_money : 0-$revision_frozen_money;
                $frozen_money = $user['frozen_money']+$frozen_money;    //计算用户被冻结的资金
                if($f_op_type==1 and $revision_frozen_money > $user['user_money'])
                {
                    exit(json_encode(['status'=>0,'msg'=>"用户剩余资金不足！！"]));
                }
                if($f_op_type==0 and $revision_frozen_money > $user['frozen_money'])
                {
                    exit(json_encode(['status'=>0,'msg'=>"冻结的资金不足！！"]));
                }
                $user_money = $f_op_type ? 0-$revision_frozen_money : $revision_frozen_money ;    //计算用户剩余资金
                M('users')->where('user_id',$user_id)->update(['frozen_money' => $frozen_money]);
            }
            if(accountLog($user_id,$user_money,$pay_points,$desc,0))
            {
                exit(json_encode(['status'=>1,'msg'=>"操作成功",'url'=>url("Admin/User/account_log",array('id'=>$user_id))]));
            }else{
                exit(json_encode(['status'=>-1,'msg'=>"操作失败"]));
            }
            exit;
        }
        $this->assign('user_id',$user_id);
        $this->assign('user',$user);
        return $this->fetch();
    }
    
    public function recharge(){
    	$timegap = urldecode(input('timegap'));
    	$nickname = input('nickname');
    	$map = array();
    	if($timegap){
    		$gap = explode(',', $timegap);
    		$begin = $gap[0];
    		$end = $gap[1];
    		$map['ctime'] = array('between',array(strtotime($begin),strtotime($end)));
    	}
    	if($nickname){
    		$map['nickname'] = array('like',"%$nickname%");
    	}  	
    	$count = M('recharge')->where($map)->count();
    	$page = new Page($count, Config::get('paginate.list_rows'));
    	$lists  = M('recharge')->where($map)->order('ctime desc')->limit($page->firstRow.','.$page->listRows)->select();
    	$this->assign('page',$page->show());
        $this->assign('pager',$page);
    	$this->assign('lists',$lists);
    	return $this->fetch();
    }
    
    public function level(){
    	$act = $this->request->param('act', 'add');
    	$this->assign('act', $act);
    	$level_id = $this->request->param('level_id');
    	if($level_id){
    		$level_info = M('user_level')->where('level_id='.$level_id)->find();
    		$this->assign('info',$level_info);
    	}
    	return $this->fetch();
    }
    
    public function levelList(){
    	$Ad =  M('user_level');
        $p = $this->request->param('p');
    	$res = $Ad->order('level_id')->page($p.',10')->select();
    	if($res){
    		foreach ($res as $val){
    			$list[] = $val;
    		}
    	}
    	$this->assign('list',$list);
    	$count = $Ad->count();
    	$Page = new Page($count,Config::get('paginate.list_rows'));
    	$show = $Page->show();
    	$this->assign('page',$show);
    	return $this->fetch();
    }

    /**
     * 会员等级添加编辑删除
     */
    public function levelHandle()
    {
        $data = input('post.');
        $userLevelValidate = Loader::validate('UserLevel');
        //$return = ['status' => 0, 'msg' => '参数错误', 'result' => ''];//初始化返回信息
        $result['result'] = '';
        $code = 0;
        $msg = '参数错误';
        if ($data['act'] == 'add') {
            if (!$userLevelValidate->batch()->check($data)) {
                $result['result'] = $userLevelValidate->getError();
                $code = 0;
                $msg = '添加失败';
            } else {
                $r = M('user_level')->strict(false)->insert($data);
                if ($r !== false) {
                    $result['result'] = $userLevelValidate->getError();
                    $result['href'] = url('Admin/User/levelList');
                    $code = 1;
                    $msg = '添加成功';
                } else {
                    $code = 0;
                    $msg = '添加失败，数据库未响应';
                }
            }
        }
        if ($data['act'] == 'edit') {
            if (!$userLevelValidate->scene('edit')->batch()->check($data)) {
                $result['result'] = $userLevelValidate->getError();
                $code = 0;
                $msg = '编辑失败';
            } else {
                $r = M('user_level')->where('level_id=' . $data['level_id'])->strict(false)->update($data);
                if ($r !== false) {
                    $discount = $data['discount']/100;
                    M('users')->where(['level'=>$data['level_id']])->update(['discount'=>$discount]);
                    $result['result'] = $userLevelValidate->getError();
                    $result['href'] = url('Admin/User/levelList');
                    $code = 1;
                    $msg = '编辑成功';
                } else {
                    $code = 0;
                    $msg = '编辑失败，数据库未响应';
                }
            }
        }
        if ($data['act'] == 'del') {
            $r = M('user_level')->where('level_id=' . $data['level_id'])->delete();
            if ($r !== false) {
                $code = 1;
                $msg = '删除成功';
            } else {
                $code = 0;
                $msg = '删除失败';
            }
        }
        $this->result($result, $code, $msg);
    }

    /**
     * 搜索用户名
     */
    public function search_user()
    {
        $search_key = trim(input('search_key'));
        if ($search_key == '') exit(json_encode(['status'=>-1,'msg'=>'请按要求输入！！']));
        $list = M('users')->where(['nickname'=>['like',"%$search_key%"]])->select();
        if ($list){
            exit(json_encode(['status'=>1,'msg'=>'获取成功','result'=>$list]));
        }
        exit(json_encode(['status'=>-1,'msg'=>'未查询到相应数据！！']));
    }
    
    /**
     * 分销树状关系
     */
    public function ajax_distribut_tree()
    {
          $list = M('users')->where("first_leader = 1")->select();
          return $this->fetch();
    }

    /**
     *
     * @time 2016/08/31
     * @author dyr
     * 发送站内信
     */
    public function sendMessage()
    {
        $user_id_array = input('get.user_id_array');
        $users = array();
        if (!empty($user_id_array)) {
            $users = M('users')->field('user_id,nickname')->where(array('user_id' => array('IN', $user_id_array)))->select();
        }
        $this->assign('users',$users);
        return $this->fetch();
    }

    /**
     * 发送系统消息
     * @author dyr
     * @time  2016/09/01
     */
    public function doSendMessage()
    {
        $call_back = input('call_back');//回调方法
        $text= input('post.text');//内容
        $type = input('post.type', 0);//个体or全体
        $admin_id = session('admin_id');
        $users = input('post.user/a');//个体id
        $message = array(
            'admin_id' => $admin_id,
            'message' => $text,
            'category' => 0,
            'send_time' => time()
        );

        if ($type == 1) {
            //全体用户系统消息
            $message['type'] = 1;
            M('Message')->insert($message);
        } else {
            //个体消息
            $message['type'] = 0;
            if (!empty($users)) {
                $create_message_id = M('Message')->insert($message);
                foreach ($users as $key) {
                    M('user_message')->insert(array('user_id' => $key, 'message_id' => $create_message_id, 'status' => 0, 'category' => 0));
                }
            }
        }
        echo "<script>parent.{$call_back}(1);</script>";
        exit();
    }

    /**
     *
     * @time 2016/09/03
     * @author dyr
     * 发送邮件
     */
    public function sendMail()
    {
        $user_id_array = input('get.user_id_array');
        $users = array();
        if (!empty($user_id_array)) {
            $user_where = array(
                'user_id' => array('IN', $user_id_array),
                'email' => array('neq', '')
            );
            $users = M('users')->field('user_id,nickname,email')->where($user_where)->select();
        }
        $this->assign('smtp', tpCache('smtp'));
        $this->assign('users', $users);
        return $this->fetch();
    }

    /**
     * 发送邮箱
     * @author dyr
     * @time  2016/09/03
     */
    public function doSendMail()
    {
        $call_back = input('call_back');//回调方法
        $message = input('post.text');//内容
        $title = input('post.title');//标题
        $users = input('post.user/a');
        $email= input('post.email');
        if (!empty($users)) {
            $user_id_array = implode(',', $users);
            $users = M('users')->field('email')->where(array('user_id' => array('IN', $user_id_array)))->select();
            $to = array();
            foreach ($users as $user) {
                if (check_email($user['email'])) {
                    $to[] = $user['email'];
                }
            }
            $res = send_email($to, $title, $message);
            echo "<script>parent.{$call_back}({$res['status']});</script>";
            exit();
        }
        if($email){
            $res = send_email($email, $title, $message);
            echo "<script>parent.{$call_back}({$res['status']});</script>";
            exit();
        }
    }

    /**
     * 提现申请记录
     */
    public function withdrawals()
    {
    	$this->get_withdrawals_list();
        $this->assign('withdraw_status',Config::get('WITHDRAW_STATUS'));
        return $this->fetch();
    }
    
    public function get_withdrawals_list($status=''){
    	$user_id = input('user_id/d');
    	$realname = input('realname');
    	$bank_card = input('bank_card');
    	$create_time = input('create_time');
    	$create_time = str_replace("+"," ",$create_time);
    	$create_time2 = $create_time  ? $create_time  : date('Y-m-d',strtotime('-1 year')).' - '.date('Y-m-d',strtotime('+1 day'));
    	$create_time3 = explode(' - ',$create_time2);
    	$this->assign('start_time',$create_time3[0]);
    	$this->assign('end_time',$create_time3[1]);
    	$where['w.create_time'] =  array('gt', strtotime($create_time3[0]), array('lt', strtotime($create_time3[1])));
    	$status = empty($status) ? input('status') : $status;
        if($status !== ''){
            $where['w.status'] = $status;
        }else{
            $where['w.status'] = ['lt',2];
        }
    	$user_id && $where['u.user_id'] = $user_id;
    	$realname && $where['w.realname'] = array('like','%'.$realname.'%');
    	$bank_card && $where['w.bank_card'] = array('like','%'.$bank_card.'%');
    	$export = input('export');
    	if($export == 1){
    		$strTable ='<table width="500" border="1">';
    		$strTable .= '<tr>';
    		$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">申请人</td>';
    		$strTable .= '<td style="text-align:center;font-size:12px;" width="100">提现金额</td>';
    		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">银行名称</td>';
    		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">银行账号</td>';
    		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">开户人姓名</td>';
    		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">申请时间</td>';
    		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">提现备注</td>';
    		$strTable .= '</tr>';
    		$remittanceList = Db::name('withdrawals')->alias('w')->field('w.*,u.nickname')->join('__USERS__ u', 'u.user_id = w.user_id', 'INNER')->where($where)->order("w.id desc")->select();
    		if(is_array($remittanceList)){
    			foreach($remittanceList as $k=>$val){
    				$strTable .= '<tr>';
    				$strTable .= '<td style="text-align:center;font-size:12px;">'.$val['nickname'].'</td>';
    				$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['money'].' </td>';
    				$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['bank_name'].'</td>';
    				$strTable .= '<td style="vnd.ms-excel.numberformat:@">'.$val['bank_card'].'</td>';
    				$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['realname'].'</td>';
    				$strTable .= '<td style="text-align:left;font-size:12px;">'.date('Y-m-d H:i:s',$val['create_time']).'</td>';
    				$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['remark'].'</td>';
    				$strTable .= '</tr>';
    			}
    		}
    		$strTable .='</table>';
    		unset($remittanceList);
    		downloadExcel($strTable,'remittance');
    		exit();
    	}
    	$count = Db::name('withdrawals')->alias('w')->join('__USERS__ u', 'u.user_id = w.user_id', 'INNER')->where($where)->count();
    	$Page  = new Page($count,20);
    	$list = Db::name('withdrawals')->alias('w')->field('w.*,u.nickname')->join('__USERS__ u', 'u.user_id = w.user_id', 'INNER')->where($where)->order("w.id desc")->limit($Page->firstRow.','.$Page->listRows)->select();
    	$this->assign('create_time',$create_time2);
    	$show  = $Page->show();
    	$this->assign('show',$show);
    	$this->assign('list',$list);
    	$this->assign('pager',$Page);
    	Config::set('TOKEN_ON',false);
    }
    
    /**
     * 删除申请记录
     */
    public function delWithdrawals()
    {
        $id = input('del_id/d');
        $res = Db::name("withdrawals")->where(['id'=>$id])->delete();
        if($res !== false){
            $return_arr = ['status' => 1,'msg' => '操作成功','data'  =>'',];
        }else{
            $return_arr = ['status' => -1,'msg' => '删除失败','data'  =>'',];
        }
        $this->ajaxReturn($return_arr);
    }

    /**
     * 修改编辑 申请提现
     */
    public  function editwithdrawals(){        
       $id = input('id');
       $withdrawals = Db::name("withdrawals")->find($id);
       $user = M('users')->where(['user_id' => $withdrawals['user_id']])->find();
       if($user['nickname'])        
           $withdrawals['user_name'] = $user['nickname'];
       elseif($user['email'])        
           $withdrawals['user_name'] = $user['email'];
       elseif($user['mobile'])        
           $withdrawals['user_name'] = $user['mobile'];
        $status = $withdrawals['status'];
        $withdrawals['status_code'] = Config::get('WITHDRAW_STATUS')["$status"];
       $this->assign('user',$user);
       $this->assign('data',$withdrawals);
       return $this->fetch();
    }  

    /**
     *  处理会员提现申请
     */
    public function withdrawals_update(){
    	$id_arr = input('id/a');
        $data['status']=$status = input('status');
    	$data['remark'] = input('remark');
        if($status == 1) $data['check_time'] = time();
        if($status != 1) $data['refuse_time'] = time();
        $ids = implode(',',$id_arr);
        $r = Db::name('withdrawals')->whereIn('id',$ids)->update($data);
    	if($r !== false){
    		exit(json_encode(array('status'=>1,'msg'=>"操作成功")));
    	}else{
    		exit(json_encode(array('status'=>0,'msg'=>"操作失败")));
    	}  	
    }
    // 用户申请提现
    public function transfer(){
        $id = I('selected/a');
        if(empty($id))$this->error('请至少选择一条记录');
        $atype = I('atype');
        if(is_array($id)){
            $withdrawals = M('withdrawals')->where('id in ('.implode(',', $id).')')->select();
        }else{
            $withdrawals = M('withdrawals')->where(array('id'=>$id))->select();
        }
        $alipay['batch_num'] = 0;
        $alipay['batch_fee'] = 0;
        foreach($withdrawals as $val){
            $user = M('users')->where(array('user_id'=>$val['user_id']))->find();
            if($user['user_money'] < $val['money'])
            {
                $data = array('status'=>-2,'remark'=>'账户余额不足');
                M('withdrawals')->where(array('id'=>$val['id']))->update($data);
                $this->error('账户余额不足');
            }else{
                $rdata = array('type'=>1,'money'=>$val['money'],'log_type_id'=>$val['id'],'user_id'=>$val['user_id']);
                if($atype == 'online'){
            
                    if($val['bank_name'] == '支付宝'){
                        //数据格式为：流水号1^收款方账号1^收款账号姓名1^付款金额1^备注说明1|流水号2^收款方账号2^收款账号姓名2^付款金额2^备注说明2
                        $alipay['batch_no'] = date('YmdHis').mt_rand(100, 999).'u';
                        $alipay['batch_fee'] += $val['money'];
                        $alipay['batch_num'] += 1;
                        $str = isset($alipay['detail_data']) ? '|' : '';
                        $alipay['detail_data'] .= $str.$val['id'].'^'.$val['bank_card'].'^'.$val['realname'].'^'.$val['money'].'^'.$val['remark'];
                    }else if($val['bank_name'] == '微信'){
                        $wxpay = array(
                                'userid' => $val['user_id'],//用户ID做更新状态使用
                                'openid' => $user['openid'],//收款人微信号对应的 OPENID
                                'pay_code'=>$val['user_id'].$val['id'].date('YmdHis'),//商户订单号，需要唯一
                                'money' => $val['money'],//金额
                                'desc' => '恭喜您提现申请成功!'
                        );
                        include_once  PLUGIN_PATH."payment/weixin/weixin.class.php";
                        $wxpay_obj = new \weixin();
                        $res = $wxpay_obj->transfer($wxpay);//微信在线付款转账
                        if($res['partner_trade_no']){
                            accountLog($val['user_id'], ($val['money'] * -1), 0,"平台处理用户提现申请");
                            M('withdrawals')->where(array('id'=>$val['id']))->update(array('status'=>2,'pay_time'=>time(),'pay_code'=>$res['partner_trade_no']));
                            expenseLog($rdata);
                        }else{
                            $this->error($res['msg']);
                        }
                    }else{
                        $this->error('由于银联不提供在线付款接口，所以银行卡提现不支持在线转账');
                    }
                
                }else{
                    // accountLog($val['user_id'], ($val['money'] * -1), 0,"管理员处理用户提现申请");//手动转账，默认视为已通过线下转方式处理了该笔提现申请
                    $r = M('withdrawals')->where(array('id'=>$val['id']))->update(array('status'=>2,'pay_time'=>time()));
                    // 解冻金额
                    $thaw = M('users')->where(array('user_id'=>$val['user_id']))->update(array('frozen_money'=>0));
                    expenseLog($rdata);//支出记录日志
                }
            }
        }
        if($alipay['batch_num']>0){
            //支付宝在线批量付款
            include_once  PLUGIN_PATH."payment/alipay/alipay.class.php";
            $alipay_obj = new \alipay();
            $alipay_obj->transfer($alipay);
        }
        $this->success("操作成功!",url('remittance'),3);
    }
    
    /**
     *  转账汇款记录
     */
    public function remittance(){
    	$status = input('status',1);
    	$this->assign('status',$status);
    	$this->get_withdrawals_list($status);
        return $this->fetch();
    }

        /**
     * 签到列表
     * @date 2017/09/28
     */
    public function signList() {       
    header("Content-type: text/html; charset=utf-8");
        exit("请联系瑾梦官网客服购买高级版支持此功能");
    }
    
    
    /**
     * 会员签到 ajax
     * @date 2017/09/28
     */
    public function ajaxsignList() {
    header("Content-type: text/html; charset=utf-8");
        exit("请联系瑾梦官网客服购买高级版支持此功能");
    }
    
    /**
     * 签到规则设置 
     * @date 2017/09/28
     */
    public function signRule() {
    header("Content-type: text/html; charset=utf-8");
        exit("请联系瑾梦官网客服购买高级版支持此功能");
    }
    /**
    * 会员增票资质
    */
    public function aptitude()
    {
        // 查询增票资质表
        $list = Db::name('users_vat_invoices_info')->select();
        $this->assign('list',$list);
        return $this->fetch();
    }
    // 审核增票资质
    public function aptitude_detail()
    {
        $id = $this->request->param('id/d');
        $row = Db::name('users_vat_invoices_info')->where("id=$id")->find();
        $this->assign('row',$row);
        return $this->fetch();
    }
    public function audit()
    {
        if ($this->request->isAjax()) {
            $audit_status = input('post.audit_status');
            $id = input('post.id');
            $res = Db::name('users_vat_invoices_info')->where('id = '.$id)->update(array('audit_status'=>$audit_status));
            if ($res !== false) {
               return array('status' => 1, 'msg' => '操作成功', 'data' => '');
            }else{
                return array('status' => 0, 'msg' => '操作失败', 'data' => '');
            }
        }
    }
    // 删除增票资质
    public function aptitude_del()
    {
        if ($this->request->isAjax()) {
            $id = input('get.id');
            $res = Db::name('users_vat_invoices_info')->where('id = '.$id)->delete();
            if ($res !== false) {
                return array('status' => 1, 'msg' => '操作成功', 'data' => '');
            }else{
                return array('status' => 0, 'msg' => '操作失败', 'data' => '');
            }
        }
    }
    /**
    * 用户留言
    */
    public function message()
    {
        $condition = [];
        if ($this->request->isPost()) {
           // 搜索条件
           $condition = array();
           $param = input('post.');
           isset($param['msg_title']) ? $condition['msg_title'] = array('like',input('msg_title').'%') : false;
           isset($param['msg_type']) ? $condition['msg_type']   = input('msg_type') : false;
           isset($param['msg_content']) ? $condition['msg_content'] = array('like',input('msg_content').'%') : false;
           $this->assign('param',$param);
           $msgList = $this->ajaxmsg($condition);
        }

        $data = $this->ajaxmsg($condition);
       
        $this->assign('msgList',$data['msgList']);
        $this->assign('page',$data['show']);// 赋值分页输出
        return $this->fetch();
    }
    public function ajaxmsg($condition) {
        
        $model = M('feedback');
        $condition['parent_id'] = 0;
        $count = $model->where($condition)->count();

        $Page  = new AjaxPage($count,Config::get('paginate.list_rows'));
        $msgList = $model->where($condition)->order('msg_time','desc')->limit($Page->firstRow.','.$Page->listRows)->select();
        
        $show = $Page->show();
        
        $data = [];
        $data['msgList'] = $msgList;
        $data['show']    = $show;
        return $data;
    }
    /**
    * 管理员回复留言
    */
    public function message_detail()
    {
        $id = I('get.id');
        if ($this->request->isPost()) {
           $param = I('post.');
           $data = [];
           $data['parent_id'] = $param['msg_id'];
           $data['user_id'] = $param['user_id'];
           $data['user_name'] = Db::name('admin')->where(array('admin_id'=>session('admin_id')))->field('user_name')->find();
           $data['msg_title'] = 'reply';
           $data['msg_type'] = 0;
           $data['msg_status'] = 0;
           $data['msg_content'] = $param['msg_content'];
           $data['msg_time'] = time();
           $data['message_img'] = 0;
           $data['order_id'] = 0;
           $data['msg_area'] = 0;
           $find = Db::name('feedback')->where(array('parent_id'=>$param['msg_id']))->find();
           if (!empty($find)) {
              $res = Db::name('feedback')->where(array('msg_id'=>$find['msg_id']))->update($data);
           }else{
              $res = Db::name('feedback')->insert($data);
           }
           
           if ($res) {
              $up = Db::name('feedback')->where(array('msg_id'=>$param['msg_id']))->update(array('msg_status'=>1));
              if ($up !== false) {
                  $this->success('回复成功！');
              }else{
                $this->error('回复失败，请稍后重试');
              }
           }
           
        }
        $row = Db::name('feedback')->where(array('msg_id'=>$id))->find();
        if ($row['msg_status'] == 1) {
            $huifu = Db::name('feedback')->where(array('parent_id'=>$id))->find();
            $this->assign('huifu',$huifu);
        }
        $this->assign('row',$row);
        return $this->fetch();
    }
    /**
    * 删除用户留言
    */
    public function del_message()
    {
        $id = I('get.id');
        $del = Db::name('feedback')->where(array('msg_id'=>$id))->delete();
        if ($del !== false) {
            return array('status'=>1,'msg'=>'删除成功','data'=>'');
           // $this->ajaxReturn(array('status'=>1,'msg'=>'删除成功','data'=>''));
        }else{
            return array('status'=>0,'msg'=>'删除失败，系统内部出现错误','data'=>'');
           // $this->ajaxReturn(array('status'=>0,'msg'=>'删除失败，系统内部出现错误','data'=>''));
        }
    }
}